package com.mairuide.base_dict.special_dates.service;

import com.mairuide._frame.utils.Testtrans;
import com.mairuide.base_dict.special_dates.dao.SpecialDatesDao;
import com.mairuide.base_dict.special_dates.dto.SpecialDatesDto;
import com.mairuide.base_dict.special_dates.pojo.SpecialDates;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.entity.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.List;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-06-04 11:31
 */
@Service
public class SpecialDatesService {
    @Autowired
    SpecialDatesDao specialDatesDao;
    @PersistenceContext
    private EntityManager entityManager;
    public void save(SpecialDates sd){
        String specialDatesTemp = sd.getSpecialDatesTemp();
        Timestamp timestamp = DateUtils.stringToTimestamp(specialDatesTemp);
        sd.setSpecialDates(timestamp);
        specialDatesDao.save(sd);
    }
    public SpecialDates findOnebyId(Integer id){
        SpecialDates specialDates = specialDatesDao.findOne(id);
        return specialDates;
    }
    public void del(Integer id){
        specialDatesDao.delete(id);
    }
    public PageResult findByPage(SpecialDatesDto dto){
        PageResult result = createSpecification(dto);
        return result;
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private PageResult createSpecification(SpecialDatesDto dto) {
        String sql = "select * from TB_SPECIAL_DATES where 1=1 ";
        if (StringUtils.isNotBlank(dto.getSpecialDates())){
            sql += " and to_char(special_dates,'yyyy-MM-dd') ='" + dto.getSpecialDates() +"'" ;
        }
        if (StringUtils.isNotBlank(dto.getDateMean())){
            sql +=" and date_mean like '%"+dto.getDateMean()+"%' ";
        }
        Query query = entityManager.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(new Testtrans(SpecialDates.class));
        List<SpecialDates> maps = query.getResultList();
        // 设置分页
        query.setFirstResult((dto.getPage() - 1) * dto.getRows());
        query.setMaxResults(dto.getRows());
        // 获取查询结果集
        List<SpecialDates> list = query.getResultList();
        PageResult pageResult = new PageResult(Long.valueOf(maps.size()), list);
        return pageResult;
    }
}
